<?php
/**
 * Created by PhpStorm.
 * User: zhangpeng
 * Date: 2017-02-27
 * Time: 下午 4:16
 */

namespace app\common\model;


use think\Db;

class Account
{
    var $config;
    var $userId;
    function __construct()
    {
        $user = $this->user = new User;
        //获取user_id
        if (!$this->userId) {
            $userId = $this->userId = $user->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }

    //管理员生成充值订单
    function orderCreateByAdmin($user_id, $total_fee) {
        //权限判断
        if(!model('Admin')->is('client')['state']){
           return [
               'state' => 0,
               'errormsg' => 'autnhority incorrect'
           ];
        }
        if (!$user_id){
            return [
                'state' => 0,
                'errormsg' => 'need user_id'
            ];
        }
        if (!$total_fee){
            return [
                'state' => 0,
                'errormsg' => 'need total_fee'
            ];
        }
        //检查total_fee
        if (!is_numeric($total_fee) || $total_fee <= 0) {
            return [
                'state' => 0,
                'errormsg' => 'total_fee error'
            ];
        }
        $demand = 'recharge';
        $config = getConfig("product");
        $data['class'] = $config['recharge']['id'];
        $data['user_id'] = $user_id;
        $data['state'] = 1;
        $data['admin_user_id'] = model('User')->getUserId();
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['total_fee'] = $total_fee;
        $ret = model('Order')->add($demand,$data);
        return $ret;
    }
    //用户生成充值订单
    public function orderCreateByUser($total_fee){
        if(!$this->userId){
            return [
                'state' => 0,
                'errormsg' => 'not find user exist'
            ];
        }
        //检查total_fee
        if (!is_numeric($total_fee) || $total_fee <= 0) {
            return [
                'state' => 0,
                'errormsg' => 'total_fee error'
            ];
        }
        if (!$total_fee){
            return [
                'state' => 0,
                'errormsg' => 'need total_fee'
            ];
        }
        $member = model('member')->getInfoByIdUserId($this->userId);
        if(!$member['state']){
            return ['state'=>0,'errormsg'=>'不能充值'];
        }
        if($member['data'][0]['key']=='vip2017'){
            if($total_fee<50000){
                return ['state'=>0,'errormsg'=>'至少充值500'];
            }
        }
        if($member['data'][0]['key']=='cluber2017'){
            if($total_fee<20000){
                return ['state'=>0,'errormsg'=>'至少充值200'];
            }
        }
        $demand = 'recharge';
        $config = getConfig("product");
        $data['class'] = $config['recharge']['id'];
        $data['user_id'] = $this->userId;
        $data['state'] = 1;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['total_fee'] = $total_fee;
        $ret = model('Order')->add($demand, $data);
        return $ret;
    }
    //查询账户余额
    function getBalanceByUserId($user_id) {
        $prefix = config('database.prefix');

        $res = Db::table($prefix.'order')
            ->alias('a')
            ->join($prefix.'pay b','a.order_id = b.order_id')
            ->where('a.class','0')
            ->where('a.user_id',$user_id)
            ->select();
        //计算充值总金额
        $recharge = 0;
        foreach ($res as $re){
            $recharge += $re['total_fee'];
        }
        //充值订单退款
        $res_pay = Db::table($prefix.'order')
            ->alias('a')
            ->join($prefix.'pay_refund b','a.order_id=b.order_id')
            ->where('a.class = 0')
            ->where('a.user_id',$user_id)
            ->select();
        $recharge_refund = 0;
        foreach ($res_pay as $value){
            $recharge_refund += $value['refund_fee'];
        }
        //刷卡消费
        $user_pay_info = Db::table($prefix.'order')
            ->alias('a')
            ->join($prefix.'pay b','a.order_id=b.order_id')
            ->field('a.user_id,b.total_fee,a.order_id')
            ->where('a.class != 0 ')
            ->where('b.user_id',$user_id)
            ->where('b.channel','2')
            ->select();
        $total_fee_a = 0;
        foreach ($user_pay_info as $value){
            $order_card_id[] = $value['order_id'];
            $total_fee_a += $value['total_fee'];
        }
        //刷卡退款
        $total_fee_refund = 0;
        if(isset($order_card_id) && $order_card_id){
            $order_id = implode(',',$order_card_id);
            $user_pay_refund = Db::name('pay_refund')
                ->where("order_id in($order_id)")
                ->select();
            foreach ($user_pay_refund as $v){
                if (isset($v['refund_fee'])){
                    $total_fee_refund += $v['refund_fee'];
                }
            }
        }
        //会员卡余额
        $member['balance'] = $recharge - $recharge_refund - $total_fee_a + $total_fee_refund;
        return [
            'state' => '1',
            'data' => [
                'balance' => $member['balance']
            ]
        ];
    }
    //获取用户充值记录
    function getRrecordListForAdmin($filter,$demand='',$unpaid=false,$channel) {
        //权限判断
        if(!model('Admin')->is('client')['state']){
            return [
                'state' => 0,
                'errormsg' => 'autnhority incorrect'
            ];
        }
        $user_ids = '';
        $admin_ids = '';
        $where="b.class = 0";
        $where_b = "";
        $order = 'b.create_time desc';
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'];
        } else {
            $pages = 1;
        }

        if(isset($filter['keywords'])&& $filter['keywords']!=""){
            $user = model('user')->exist(['tel'=>$filter['keywords']]);
            if($user['state']){
                $user_ids = $admin_ids = $user['data']['user_id'];
                $where .= " and b.user_id=$user_ids";
                $where_b = "user_id=$user_ids";
            }else{
                $card = model('card')->getUserIdByCode($filter['keywords']);
                if($card['state']){
                    $user_ids = $admin_ids = $card['data']['user_id'];
                    $where .= " and b.user_id=$user_ids";
                    $where_b = "user_id=$user_ids";
                }else{
                    if(is_numeric($filter['keywords'])){
                        $where .= " and b.order_id=".$filter['keywords'];
                        $where_b = "order_id=".$filter['keywords'];
                    }else{
                        $user_wh = keywordSQL($filter['keywords'],'set_name,nickname,real_name');
                        $user = Db::name('user')->where($user_wh)->select();
                        if (!$user){
                            return ['state'=>0,'errormsg'=> 'user notfind'];
                        }$ids = '';
                        foreach ($user as $k=>$v){
                            $ids .= $v['user_id'].',';
                        }
                        $ids = substr($ids,0,-1);
                        $where .= " and b.user_id in ($ids)";
                        $where_b .= "user_id in ($ids)";
                    }
                }
            }
        }
        if($channel){
            switch ($channel) {
                case "cashpay":
                    $where .= " and a.channel = 1";
                    break;
                case "accountpay":
                    $where .= " and a.channel = 2";
                    break;
                case "wxpay":
                    $where .= " and a.channel = 101";
                    break;
                case "alipay":
                    $where .= " and a.channel = 201";

            }
        }
        if (isset($filter['order'])&&$filter['order']){
            $order = 'b.create_time asc';
        }
        $prefix = config('database.prefix');
        //当前时间区间
        $todayTime = strtotime(date('Ymd'));
        $yesterday = strtotime(date('Ymd')) + 86400;
        $res = Db::table($prefix.'pay')
            ->alias('a')
            ->join($prefix.'order b','a.order_id = b.order_id')
            ->where($where)
            ->order($order)
            ->paginate(12,false,['page'=>$pages]);

        //统计今日
        if ($demand == 'statisics'){
            $res = Db::table($prefix.'pay')
                ->alias('a')
                ->join($prefix.'order b','a.order_id = b.order_id')
                ->where('b.create_time','EGT',$todayTime)
                ->where('b.create_time','ELT',$yesterday)
                ->where($where)
                ->order($order)
                ->paginate(12,false,['page'=>$pages]);
        }
        if($unpaid==true){
            $res = Db::name('order')
                ->where('class',0)
                ->where("not exists(select * from ".$prefix."pay where order_id = ".$prefix."order.order_id)")
                ->where($where_b)
                ->order('create_time desc')
                ->paginate(12,false,['page'=>$pages]);
        }
        $page = $res->render();
        $res = $res->items();
        $record = [];
        foreach ($res as $k => $v) {
            $tel = model('user')->getInfoById($v['user_id']);
            $record[$k]['tel'] = isset($tel['tel']) ? $tel['tel'] : "";
            $record[$k]['create_time'] = $v['create_time'];
            $record[$k]['total_fee'] = $v['total_fee'];
            $record[$k]['order_id'] = $v['order_id'];
            $record[$k]['user_id'] = $v['user_id'];
            $user_info = model('user')->getInfoById($v['user_id']);
            $record[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : userTextDecode($user_info['user_name']);

            if ($v['admin_user_id']) {
                $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
                $record[$k]['admin_user_name'] = isset($admin_user_info['set_name'])? $admin_user_info['set_name']:$admin_user_info['user_name'];
            } else {
                $record[$k]['admin_user_name'] = "";
            }
            //支付渠道
            if(isset($v['channel'])) {
                switch ($v['channel']) {
                    case 1:
                        $record[$k]['cashpay'] = 1;
                        break;
                    case 2:
                        $record[$k]['accountpay'] = 1;
                        break;
                    default:
                        switch ((int)($v['channel'] / 100)) {
                            case 1:
                                $record[$k]['wxpay'] = 1;
                                break;
                            case 2:
                                $record[$k]['alipay'] = 1;
                                break;
                        }
                }
            }else{
                $record[$k]['unpaid'] = 1;
            }
            //计算充值退款金额
            $order_id = $v['order_id'];
            $pay_refund = Db::name('pay_refund')->where("order_id = '$order_id'")->select();

            $refund_total_fee = 0;
            if (isset($pay_refund)&&$pay_refund){
                foreach ($pay_refund as $key => $value) {
                    $refund_total_fee += $value['refund_fee'];
                }
            }
            //充值订单退款
            $record[$k]['refund_fee'] = $refund_total_fee;
        }
        $page=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$page);
        $page=str_replace("&laquo;","上一页",$page);
        $page=str_replace("&raquo;","下一页",$page);
        return array('state' => 1, 'data' => array('list' => $record),'page'=>$page);
    }
    //退款清单
    public function getRefundList($demand,$fiter,$chnnel){
        $refund = model('order')->getRefundList($demand,$fiter,$chnnel);
        foreach ($refund['data']['list'] as $k => $v) {
            //支付渠道
            switch ($v['channel']) {
                case 1:
                    $refund['data']['list'][$k]['cashpay'] = 1;
                    break;
                case 2:
                    $refund['data']['list'][$k]['accountpay'] = 1;
                    break;
                default:
                    switch ((int) ($v['channel'] / 100)) {
                        case 1:
                            $refund['data']['list'][$k]['wxpay'] = 1;
                            break;
                        case 2:
                            $refund['data']['list'][$k]['alipay'] = 1;
                            break;
                    }
            }
            $user_info = model('user')->getInfoById($v['user_id']);
            $refund['data']['list'][$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : userTextDecode($user_info['user_name']);
            $refund['data']['list'][$k]['tel'] = isset($user_info['tel']) ? $user_info['tel'] : "";
            $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
            $refund['data']['list'][$k]['admin_user_name'] = $admin_user_info['set_name']?$admin_user_info['set_name']:$admin_user_info['real_name'];
        }
        return $refund;
    }
}